import Taro, { Component } from '@tarojs/taro'
import { set as setGlobalData, get as getGlobalData, set } from './global_data'
import common from '../../service/common'
import api from '../../service/api'

const env = process.env.TARO_ENV
module.exports = {
    showLoading,
    showToast,
    showModal,
    showModals,
    getSettingUserInfo,
    chooseAddress,
    chooseImage,
    scanCode,
    getExtConfig,
    setSensorsCommonParse,
    login,
    getCodeTimer,
    prevPage,
    getQueryVariable
}
function showLoading(title, mask) {
    if (!title) {
        title = "加载中..."
    }
    if (!mask) {
        mask = false
    }
    Taro.showLoading({
        title: title,
        mask: mask
    })
}
function showToast(msg,icon){
    Taro.showToast({
        title: msg,
        icon: icon
    })
}
function showModal(content, title, callback) {
    if (!title) { title = '提示' }
    Taro.showModal({
        title: title,
        content: content,
        showCancel: false,
        success: () => {
            if (callback) { callback() }
        }
    })
}
function showModals(content, title, callback) {
    if (!title) { title = '提示' }
    Taro.showModal({
        title: title,
        content: content,
        success: function (res) {
            if (callback) { callback(res) }
        }
    })
}
// 微信是否授权
function getSettingUserInfo(that, callback) {
    Taro.getSetting({
        success(res) {
            console.log(res)
            if(callback){callback(res)}
            // if (!res.authSetting['scope.userInfo']) { //没授权
            //     wx.openSetting({
            //         success: (res) => {}
            //     })
            // } else {
            // }
        }
    })
}
function chooseAddress(callback){
    Taro.chooseAddress({
        success: (res) => {
            if(callback){callback(res)}
        },
        fail: (err) => {
            console.log(err)
            getSettingUserInfo(this,(res) => {
                if(!res.authSetting['scope.address']){ //没授权
                    Taro.openSetting({
                        success: (ss) => {
                            console.log(ss)
                        }
                     })
                }
            })
        }
    })
}
// 选择图片
function chooseImage() {
    Taro.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            var tempFilePaths = res.tempFilePaths
            console.log(res)
        }
    })
}
// 扫码
function scanCode(that, callback) {
    Taro.scanCode({
        onlyFromCamera: true,
        success: (res) => {

        },
        fail: (res) => {
            showModal("您取消了扫码！")
        },
        complete: (res) => {

        }
    })
}
// 获取ext.json内容
function getExtConfig(callback){
    let env = process.env.TARO_ENV;
    if(env == 'weapp'){
        Taro.getExtConfig({
            success: res => {
                let data = res.extConfig;
                _getExtConfig(data,callback)
            }
        })
    }else if(env == 'alipay'){
        const extJson = my.getExtConfigSync();
        _getExtConfig(extJson,callback)
    } else{ //h5
        var data = {
            "vers": true,
            "name": "wechat/",
            "SHOP_NO": "100276",
            "FilePath": "https://cdn.weikebaba.com",
            "requestUrl": "https://sslzggj.weikezhanggui.com/WebInterface.ashx",
            "requestUrl0": "https://zgxcxssl.kantuzhuan.com/WebInterface.ashx",
            "requestUrl1": "https://sslzggj.weikezhanggui.com/WebInterface.ashx",
            "alipayRequestUrl": "https://sslzggj.weikezhanggui.com/api/Alipay",
            "alipayRequestUrl0": "https://zgxcxssl.kantuzhuan.com/api/Alipay",
            "bhjUrl": "https://baihuiji.weikebaba.com",
            "httpUrl": "https://sslzggj.weikezhanggui.com/",
            "http": "https://xcxapits.weikezhanggui.com/",
        }
        _getExtConfig(data,callback)
    }
}
function _getExtConfig(data,callback){
    let domain = data.requestUrl, //微信小程序请求域名
    domainImg = data.FilePath; //微信小程序图片域名
    let domainAlipay = data.alipayRequestUrl // 支付宝小程序请求域名
    if(data.vers){ //测试
        domain = data.requestUrl0
        domainImg = data.FilePath0
        domainAlipay = data.alipayRequestUrl0
    }
   
    setGlobalData("domain", domain) //全局请求地址
    setGlobalData("domainImg", domainImg) //全局图片url
    setGlobalData('bhjUrl',data.bhjUrl)
    setGlobalData('SHOP_NO',data.SHOP_NO) //全局店铺编号
    setGlobalData('domainAlipay', domainAlipay) //支付宝全局请求地址
    setGlobalData('registerAppState', false) //是否注册神策公共属性
    if(callback){callback()}
}
// 设置公共埋点
function setSensorsCommonParse(callback){
    const registerAppState = getGlobalData('registerAppState')
    const shopInfo = getGlobalData('shopInfo')
    const userInfo = getGlobalData('userInfo')
    if(!registerAppState){
        if(shopInfo && userInfo){
            if(callback){callback()}
            setGlobalData('registerAppState',true)
            const nickname = userInfo.C_MB_NICKNAME && userInfo.C_MB_NICKNAME != '' ? userInfo.C_MB_NICKNAME : userInfo.C_MB_NAME
            const datas = {
                brandId: shopInfo.kdt[0].storeshid,
                brandName: shopInfo.kdt[0].storeshname,
                shopName: shopInfo.kdt[0].storename,
                shopNumber: shopInfo.kdt[0].storeid,
                commFirstCate: shopInfo.kdt[0].yjHName,
                commSecondCate: shopInfo.kdt[0].HName != '' ? shopInfo.kdt[0].HName : shopInfo.kdt[0].yjHName,
                device_id: userInfo.C_MB_NO,
                datasourcetype: '线上', //数据来源
                MebNckName: nickname || '',   //会员昵称
                MebNo: userInfo.C_MB_NO, //会员编号
                MebLever: userInfo.C_MG_NAME || '', //会员等级
                MebType: userInfo.N_MB_TYPE, //会员类型 1 普通会员  2 加盟店 直营店会员
            }
            console.log('sensors.registerApp-----------------------------')
            console.log(datas)
            // sensors.registerApp(datas)
        } 
    }else{
        if(shopInfo && userInfo){
            if(callback){callback()}
        }
    }
}
// 登陆
function login(callback) {
    switch (env) {
        case "weapp":
            _loginWeapp(callback);
            break;
        case "alipay":
            _loginAlipay(callback);
            break;
    }
}
// 微信登陆
function _loginWeapp(callback) {
    Taro.login({
        success: function (res) {
            console.log(res)
            Taro.setStorageSync('code', res.code)
            setGlobalData('code',res.code)
            if (callback) { callback(res.code) }
        },
        fail: function (res) {
            console.log(res)
        }
    })
}
// 支付宝授权
function _loginAlipay(callback) {
    my.getAuthCode({
        scopes: 'auth_user',
        success: (res1) => {
            my.getAuthUserInfo({
                success: (userInfo) => {
                    console.log(res1.authCode)
                    setGlobalData("authorizeUserInfo", userInfo)
                    if(callback){callback(res1.authCode)}
                    console.log(getGlobalData("authorizeUserInfo"))
                }
            });
        },
        fail: (err1) => {
            console.log(err1)
            if(callback){callback()}
        }
    });
}
// 获取验证码倒计时
function getCodeTimer(time,that, callback) {
    if (!/^1\d{10}/.test(that.state.phoneNum)) {
        showToast("请先输入正确的手机号！",'none')
        that.setState({codeDisabled: false})
        return
    }
    if (callback) { callback() }
    let t = time ? time : 120;
    that.setState({
        codeVal: t + "s后获取",
        codeDisabled: true
    })
    let timer = setInterval(function () {
        if(that.state.codeVal == '获取验证码' && t < 120){
            clearInterval(timer)
        }else if (t < 1) {
            that.setState({
                codeVal: "获取验证码",
                codeDisabled: false
            })
            clearInterval(timer)
        } else {
            console.log(3)
            t--;
            that.setState({ codeVal: t + "s后获取" })
        }
        
    }, 1000)
    
}
// 获取上一页
function prevPage(num) {
    if (!num) {
        num = 2
    }
    const pages = Taro.getCurrentPages()
    const prevPage = pages[pages.length - num]
    return prevPage.$component
}
// 获取url后的参数
function getQueryVariable(url, variable) {
    let query = url.split("?");
    if (query.length > 1) {
        let vars = query[1].split("&");
        for (let i = 0; i < vars.length; i++) {
            let pair = vars[i].split("=");
            if (pair[0] == variable) { return pair[1]; }
        }
        return (false);
    }
}